package com.lingnan.tijian.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingnan.tijian.domain.Users;
import com.lingnan.tijian.dto.ApiResponse;
import com.lingnan.tijian.service.ifac.UsersService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jdk.nashorn.internal.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController  //  @Controller+@ResponseBody  表示当前类是一个servlet 同时接口返回数据都是json字符串
//@CrossOrigin(origins = "*",exposedHeaders = "token",allowedHeaders = "*")
public class UsersController {
    @Autowired
    UsersService usersService;

    /**
     * 处理前端注册功能的接口方法
     */
    @RequestMapping("register")     //那么前端递交请求，路径就是/register  这样就会交给我们这个方法来处理
    public ApiResponse register(@RequestBody Users users){  //前端与后端都是ajax交互，传递的是json字符串，  @RequestBody注解可以把json字符串转化成java对象
        return usersService.registerService(users);
    }

    /**
     * 处理前端登录功能的接口方法
     */
    @RequestMapping("login")
    public ApiResponse login(@RequestBody Users users, HttpServletResponse response) throws JsonProcessingException {

        System.out.println("进入UserController login方法。。。。。。。。。。。。。。。。");
        ApiResponse apiResponse=usersService.login(users);
        Users user=(Users)apiResponse.getData();
        if(apiResponse.getStatus()==ApiResponse.SUCCESS_STATUS){
            Map<String,Object> map=new HashMap<>();
            //map.put("currentUser",user);
            map.put("currentUser", new ObjectMapper().writeValueAsString(user));

            JwtBuilder builder= Jwts.builder()
                    .setId(UUID.randomUUID().toString())
                    .setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256,"123456-----")    //随便写，越长越好
                    .setExpiration(new Date(System.currentTimeMillis()+1000*60*20))     //改成3，方便测试
                    .setClaims(map).setSubject(user.getUserId())
                    ;
            String key=builder.compact();
            response.setHeader("token",key);
            System.out.println("返回数据给前端。。。。。。。。。。。。。。");

            return apiResponse;

        }

        //压的数据：users
        return apiResponse;
    }


}
